#!/bin/bash docker方式启动脚本，放置在远程服务docker目录下，即：DOCKER_DIR

# 设置环境变量
SERVER_NAME="boot"
CONTAINER_NAME="rcs"
IMAGE_NAME="rcs:latest"
PORT=8091
TARGET_DIR="/home/agilerobots/docker/java"
DOCKERFILE="/home/agilerobots/docker/java/Dockerfile"
LOGS_VOLUME="/home/agilerobots/docker/java/logs"
AUDIO_VOLUME="/home/agilerobots/AMR-Resources/audio/"

# 函数：日志输出
log() {
  echo "$(date +'%Y-%m-%d %H:%M:%S') - $1"
}

# 函数：检查文件或目录是否存在
check_exists() {
  if [ ! -e "$1" ]; then
    log "Error: $1 does not exist."
    exit 1
  fi
}

# 函数：检查权限
check_permissions() {
  if [ ! -r "$1" ]; then
    log "Error: No read permission for $1."
    exit 1
  fi
}

# 检查目标目录和 Dockerfile 是否存在
check_exists "$TARGET_DIR"
check_exists "$DOCKERFILE"

# 查找最新的 JAR 文件
JAR_PATTERN="${TARGET_DIR}/${SERVER_NAME}*.jar"
LATEST_JAR=$(ls -t $JAR_PATTERN 2>/dev/null | head -n 1)
if [ -z "$LATEST_JAR" ]; then
  log "Error: No .jar files found in the directory."
  exit 1
fi

# 获取 JAR 文件相对于构建上下文的路径
RELATIVE_JAR=$(realpath --relative-to="$PWD" "$LATEST_JAR")
log "Latest .jar file: $RELATIVE_JAR"

# 检查 JAR 文件的权限
check_permissions "$LATEST_JAR"

# 停止并移除旧的容器和镜像
log "Stopping and removing old container and image..."
docker stop "$CONTAINER_NAME" || true
docker rm "$CONTAINER_NAME" || true
docker rmi -f "$IMAGE_NAME" || true

# 清理未标记的镜像
# log "Cleaning up untagged images..."
# docker image prune -f

# 构建新的 Docker 镜像
log "log "Latest .jar file: $RELATIVE_JAR"Building new Docker image..."
docker build --build-arg JAR_FILE=$RELATIVE_JAR -f $DOCKERFILE -t $IMAGE_NAME .

log "Latest .jar file: $RELATIVE_JAR"# 检查构建是否成功
if [ $? -ne 0 ]; then
  log "Error: Docker build failed."
  exit 1
fi

# 运行新的 Docker 容器
log "Running new Docker container..."
docker run -d \
  -p $PORT:$PORT \
  -v $LOGS_VOLUME:/app/logs \
  -v $AUDIO_VOLUME:/home/agilerobots/AMR-Resources/audio/ \
  --name $CONTAINER_NAME $IMAGE_NAME

# 检查容器是否成功启动
if [ $? -ne 0 ]; then
  log "Error: Docker run failed."
  exit log "Latest .jar file: $RELATIVE_JAR"
fi

log "Container started successfully."
